package cn.yto.print.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {

    private static final String AES_ALGORITHM = "AES";
    private static final String HEX_CHARS = "0123456789ABCDEF";
    private static final String SECRET_KEY = "9d69e17e6b12a963a5b5f9f16b8c63c7";

    /**
     * 加密并返回十六进制字符串
     */
    public static String encryptToHex(String text) throws Exception {
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), AES_ALGORITHM);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] encryptedBytes = cipher.doFinal(text.getBytes());
        return bytesToHex(encryptedBytes);
    }

    /**
     * 解密十六进制字符串并返回原始文本
     */
    public static String decryptFromHex(String hexString) throws Exception {
        byte[] encryptedBytes = hexToBytes(hexString);
        Cipher cipher = Cipher.getInstance(AES_ALGORITHM);
        SecretKeySpec secretKey = new SecretKeySpec(SECRET_KEY.getBytes(), AES_ALGORITHM);
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes);
    }

    /**
     * 将字节数组转换成十六进制字符串
     */
    private static String bytesToHex(byte[] bytes) {
        StringBuilder hexString = new StringBuilder(2 * bytes.length);
        for (byte aByte : bytes) {
            hexString.append(HEX_CHARS.charAt((aByte & 0xF0) >> 4))
                    .append(HEX_CHARS.charAt((aByte & 0x0F)));
        }
        return hexString.toString();
    }

    /**
     * 将十六进制字符串转换成字节数组
     */
    private static byte[] hexToBytes(String hexString) {
        int len = hexString.length();
        byte[] data = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            data[i / 2] = (byte) ((Character.digit(hexString.charAt(i), 16) << 4)
                    + Character.digit(hexString.charAt(i + 1), 16));
        }
        return data;
    }

    public static void main(String[] args) {
        try {
            String originalString = "88888888";
            System.out.println("原始字符串: " + originalString);
            // 加密
            String encryptedString = encryptToHex(originalString);
            System.out.println("加密后的字符串: " + encryptedString);
            // 解密
            String decryptedString = decryptFromHex(encryptedString);
            System.out.println("解密后的字符串: " + decryptedString);
        } catch (Exception e) {
            System.err.println("发生异常: " + e.getMessage());
        }
    }

}

